package com.gary.vueblog.controller;

import cn.hutool.core.map.MapUtil;
import com.gary.vueblog.entity.MUser;
import com.gary.vueblog.entity.ResultInfo;
import com.gary.vueblog.entity.UserDTO;
import com.gary.vueblog.service.MUserService;
import com.gary.vueblog.utils.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * (MUser)表控制层
 *
 * @author makejava
 * @since 2020-12-08 10:17:25
 */
@RestController
@RequestMapping("mUser")
public class MUserController {
    /**
     * 服务对象
     */
    @Resource
    private MUserService mUserService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public MUser selectOne(Long id) {
        return this.mUserService.queryById(id);
    }

    @PostMapping("/saveUser")
    public ResultInfo saveUser(@Validated @RequestBody MUser user) {
        System.out.println(user);
        return ResultInfo.success(user);
    }

    /**
     * 登录接口
     * @param userDTO
     * @return
     */
    @PostMapping("/login")
    public ResultInfo login(@Validated @RequestBody UserDTO userDTO, HttpServletResponse response) {
        MUser mUser = mUserService.queryByUsername(userDTO.getUsername());
        Assert.notNull(mUser, "用户不存在");

        if (!mUser.getPassword().equals(userDTO.getPassword())) {
            return ResultInfo.res(600, "密码错误", null);
        }
        String jwt = jwtUtil.generateToken(mUser.getId());
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        return ResultInfo.success(MapUtil.builder()
                .put("id", mUser.getId())
                .put("username", mUser.getUsername())
                .put("email", mUser.getEmail())
                .put("avatar", mUser.getAvatar())
                .build());
    }

    /**
     *  登出
     * @return
     */
    @RequiresAuthentication
    @GetMapping("/logout")
    public ResultInfo logout() {
        SecurityUtils.getSubject().logout();
        return ResultInfo.success(null);
    }

}